package com.smartStatus.admin.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartStatus.admin.service.*;
import com.smartStatus.admin.utils.JoinUtil;
import com.smartStatus.api.dto.StudentDTO;
import com.smartStatus.api.dto.SysUserDTO;
import com.smartStatus.api.dto.SysUserImportDTO;
import com.smartStatus.api.dto.TeacherDTO;
import com.smartStatus.api.entity.*;
import com.smartStatus.api.vo.SysGradeVO;
import com.smartStatus.api.vo.SysUserVO;

import com.smartStatus.core.api.CampusUser;
import com.smartStatus.core.constant.StatusUser;
import com.smartStatus.core.constant.UserInfo;
import com.smartStatus.core.util.DesensitizationUtils;
import com.smartStatus.core.util.R;
import com.smartStatus.core.util.SecretUtils;
import com.smartStatus.data.utils.ExcelUtils;

import com.smartStatus.security.annoation.Ignore;
import com.smartStatus.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统用户表 Controller
 *
 * @author lby
 * @since 2021-01-11
 */
@RestController
@Slf4j
@Api(value = "SysUser", tags = "系统用户表管理")
@AllArgsConstructor
@RequestMapping("sysUser")
public class SysUserController {

    private final SysUserService sysUserService;
    private final SysRoleService sysRoleService;
    private final SysFileService sysFileService;
    private final SysUserTenantService sysUserTenantService;
    private final SysUserRoleService sysUserRoleService;


    /**
     * 分页数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "系统用户表分页数据")
    @GetMapping("/page")
    public R sysUserPage(Page<SysUser> page, SysUser sysUser) {
        QueryWrapper<SysUser> query = Wrappers.query();
        if (StrUtil.isNotEmpty(sysUser.getBlurry())) {
            query.like("user_name", sysUser.getBlurry());
        }
        if (sysUser.getState() != null) {
            query.eq("state", sysUser.getState());
        }
        if (sysUser.getRoleIdList() != null && sysUser.getRoleIdList().size() > 0) {
            List<Integer> idList = new ArrayList<>();
            QueryWrapper<SysUserRole> query1 = Wrappers.query();
            query1.in("role_id", sysUser.getRoleIdList());
            List<SysUserRole> sysUserRoles = sysUserRoleService.list(query1);
            if (sysUserRoles != null && sysUserRoles.size() > 0) {
                sysUserRoles.forEach(sysUserRole -> {
                    idList.add(sysUserRole.getUserId());
                });
                query.in("id", idList);
            } else {
                query.in("id", 0);
            }
        }
        // 只能看到自己租户下的数据
        Integer tenantId = SecurityUtils.getUser().getTenantId();
        if (tenantId != null && tenantId != 0) {
            List<Integer> userIdList = new ArrayList<>();
            QueryWrapper<SysUserTenant> query1 = Wrappers.query();
            query1.eq("tenant_id", tenantId);
            List<SysUserTenant> list = sysUserTenantService.list(query1);
            list.forEach(sysUserTenant -> {
                userIdList.add(sysUserTenant.getUserId());
            });
            query.in("id", userIdList);
        }
        Page<SysUser> page1 = sysUserService.page(page, query);
        Page page2 = JoinUtil.page(page1, SysUserVO.class);
        List<SysUserVO> records = (List<SysUserVO>) page2.getRecords();
        SysUser user1 = new SysUser();
        records.forEach(sysUserVO -> {
            user1.setId(sysUserVO.getId());
            List<SysRole> userRoleLists = sysRoleService.getUserRoleLists(user1);
            QueryWrapper<SysUserTenant> query1 = Wrappers.query();
            query1.eq("user_id", sysUserVO.getId());
            SysUserTenant one = sysUserTenantService.getOne(query1);
            if (one != null) {
                sysUserVO.setTenantId(one.getTenantId());
            }
            sysUserVO.setSysRoleList(userRoleLists);
//            sysUserVO.setPhone(DesensitizationUtils.mobilePhone(sysUserVO.getPhone()));
//            sysUserVO.setIdCard(DesensitizationUtils.idCardNum(sysUserVO.getIdCard()));
//            sysUserVO.setEmail(DesensitizationUtils.email(sysUserVO.getEmail()));
            userRoleLists.forEach(sysRole -> {
                ArrayList<Integer> roleIdLists = new ArrayList<>();
                roleIdLists.add(sysRole.getId());
                sysUserVO.setRoleIdList(roleIdLists);
            });
        });
        return R.ok(page2, "查询成功");
    }


    /**
     * 列表数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "系统用户表列表")
    @GetMapping("/list")
    public R sysUserList() {
        return R.ok(sysUserService.list());
    }


    /**
     * 编辑数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "编辑系统用户表")
    @ApiImplicitParam(name = "SysUser", value = "SysUser实体", required = true, dataType = "SysUser")
    @PutMapping("/edit")
    public R sysUserUpdate(@RequestBody SysUser sysUser) {
        sysRoleService.delUserRoleList(sysUser);
        for (Integer roleId : sysUser.getRoleIdList()) {
            sysUserService.saveUserRole(sysUser.getId(), roleId);
        }
        return R.ok(sysUserService.updateById(sysUser));
    }


    /**
     * 删除数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "删除系统用户表")
    @ApiImplicitParam(name = "id", value = "sys_userid", required = true, dataType = "Integer")
    @DeleteMapping("/{ids}")
    public R sysUserDelete(@PathVariable Integer[] ids) {
        for (Integer userId : ids) {
            sysUserService.removeById(userId);
        }
        return R.ok("删除成功");
    }

    /**
     * 添加数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "添加系统用户表")
    @ApiImplicitParam(name = "SysUser", value = "SysUser实体", required = true, dataType = "SysUser")
    @PostMapping("/add")
    public R sysUserInsert(@RequestBody SysUserVO sysUserVO) throws Exception {
        Boolean aBoolean = sysUserService.saveUser(sysUserVO);
        if (aBoolean) {
            return R.ok(true, "保存成功");
        } else {
            return R.failed("该用户已存在，请重试");
        }

    }

    /**
     * 导出用户数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "导出用户数据")
    @PostMapping("/export-user-list")
    public void exportUserList(@RequestBody List<SysUserVO> sysUserVOList, HttpServletResponse response) throws IOException {
        // 判断模板
        if (sysUserVOList != null && sysUserVOList.size() > 0) {
            // 数据处理
            sysUserVOList.forEach(sysUserVO -> {
                if (sysUserVO.getSex() == 0) {
                    sysUserVO.setSexName("男");
                } else {
                    sysUserVO.setSexName("女");
                }
            });
            List<Integer> roleIdList = sysUserVOList.get(0).getRoleIdList();
            // 教师
            if (roleIdList.contains(3)) {
                List<TeacherDTO> list = JoinUtil.list(sysUserVOList, TeacherDTO.class);
                ExcelUtils.exportData(TeacherDTO.class, response, list);
            } else {
                List<StudentDTO> list = JoinUtil.list(sysUserVOList, StudentDTO.class);
                ExcelUtils.exportData(StudentDTO.class, response, list);
            }
        }

    }

    /**
     * 导入用户数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "导入用户数据")
    @PostMapping("/import-user-list")
    public R importUserList(@Param("file") MultipartFile file, @Param("roleIdList") Integer roleIdList) throws Exception {
        List<SysUserImportDTO> importData = ExcelUtils.importData(file, SysUserImportDTO.class);
        List<Integer> list = new ArrayList<>();
        list.add(roleIdList);
        Map<String, Object> map = sysUserService.importUserLists(importData, list);
        if (map == null) {
            return R.failed("导入失败，时间格式错误");
        }
        return R.ok(map, "导入成功");
    }

    /**
     * 冻结用户
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "冻结用户")
    @PostMapping("/frozen-user")
    public R frozenUser(@RequestBody SysUser sysUser) {
        if (sysUser.getState() != null) {
            return R.ok(sysUser.updateById(), "修改成功");
        } else {
            return R.failed("修改失败，请重试");
        }
    }

    /**
     * 根据id获取用户
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "冻结用户")
    @PostMapping("/get-user-by-name")
    public R getUserInfoById(@RequestBody SysUser sysUser) {
        QueryWrapper<SysUser> query = Wrappers.query();
        if (sysUser.getUserName() != null) {
            query.eq("user_name", sysUser.getUserName());
        }
        if (sysUser.getId() != null) {
            query.eq("id", sysUser.getId());
        }
        return R.ok(sysUserService.getOne(query));
    }


    /**
     * 查询用户绑定年级，班级数据
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "查询用户绑定年级，班级数据")
    @PostMapping("/get-grade-classes")
    public R branchLists(@RequestBody SysUserVO sysUserVO) {
        QueryWrapper<SysUserTenant> query4 = Wrappers.query();
        query4.eq("user_id", sysUserVO.getId());
        SysUserTenant one1 = sysUserTenantService.getOne(query4);
        if (one1 == null) {
            return R.failed("未查询到当前用户租户");
        }
        Integer tenantId = one1.getTenantId();
        List<SysGradeVO> userClasses = sysUserService.getUserClasses(tenantId, sysUserVO);
        if (userClasses != null && userClasses.size() > 0) {
            return R.ok(userClasses);
        } else {
            return R.failed("未查询到系统班级数据");
        }
        // 获取年级，班级列表
    }


    /**
     * 学生绑定班级
     */
    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "学生绑定班级")
    @PostMapping("/bind-class")
    public R bindClass(@RequestBody List<SysGradeVO> sysGradeVOList) {
        if (sysGradeVOList.size() > 1 || sysGradeVOList.get(0).getSelectedChecks().size() > 1) {
            return R.failed("您只能选择一个班级");
        }
        UserClass userClass = new UserClass();
        userClass.setUserId(sysGradeVOList.get(0).getUserId());
        userClass.setClassId(sysGradeVOList.get(0).getSelectedChecks().get(0));
        return R.ok(userClass.insert());
    }


    /**
     * 用户修改个人头像
     */
    @Ignore(value = false)
//    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "用户修改个人头像")
    @PostMapping("/update-avator")
    public R updateUserAvator(@RequestParam("avatar") MultipartFile avatar, HttpServletRequest request) {
        Map<String, String> map = sysFileService.uploadFile(avatar);
        map.put("realUrl", map.get("url"));
        /*修改头像*/
        com.smartStatus.core.constant.SysUser sysUser = SecurityUtils.getUser().getSysUser();
        SysUserVO userVO = new SysUserVO();
        userVO.setAvatarUrl(map.get("url"));
        if (sysUser != null) {
            userVO.setId(sysUser.getUserId());
            userVO.updateById();
            return R.ok(map, "上传成功");
        } else {
            return R.failed("未获取用户信息");
        }

    }


    /**
     * 获取用户
     *
     * @param roleId
     * @return
     */
    @Ignore(value = false)
//    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @ApiOperation(value = "获取用户")
    @GetMapping("/list/by-role/{roleId}")
    public R getAllStudents(@PathVariable("roleId") Integer roleId) {
        return R.ok(sysUserService.getStudents(roleId));
    }


    @Ignore(value = false)
    @GetMapping("/info/{username}")
    public R getInfo(@PathVariable("username") String username) {
        QueryWrapper<SysUser> query = Wrappers.query();
        query.eq("user_name", username);
        SysUser one = sysUserService.getOne(query);
        if (one == null) {
            return R.failed("未查询到当前用户");
        }
        UserInfo userInfo = new UserInfo();
        // 给用户赋予权限与角色
        Map<String, Object> userRoles = sysUserService.getUserRoles(one);
        userInfo.setPermissions((String[]) userRoles.get("pre"));
        userInfo.setRoles((Integer[]) userRoles.get("role"));
        com.smartStatus.core.constant.SysUser sysUser = new com.smartStatus.core.constant.SysUser();
        sysUser.setUsername(one.getUserName());
        sysUser.setPassword(one.getPassword());
        sysUser.setLockFlag("0");
        sysUser.setUserId(one.getId());
        // 获取用户tenantnId
        QueryWrapper<SysUserTenant> query1 = Wrappers.query();
        query1.eq("user_id", one.getId());
        SysUserTenant one1 = sysUserTenantService.getOne(query1);
        if (one1 == null) {
            return R.failed("未获取到当前用户所在租户");
        }
        sysUser.setTenantId(one1.getTenantId());
        userInfo.setSysUser(sysUser);
        return R.ok(userInfo);
    }


    @Ignore(value = false)
//    @PreAuthorize("@pms.hasPermission('sys_user_view')")
    @GetMapping("/user-info")
    public R getInfo() {
        return sysUserService.getUserInfo();
    }


    @Ignore(value = false)
    @GetMapping("/get-by-id/{userId}")
    public R getUserInfoById(@PathVariable("userId") String userId) {
        return R.ok(sysUserService.getById(userId));
    }


}
